﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RedisDemo.Models;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Configuration;
using RestSharp;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;

namespace RedisDemo.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        IConfiguration config;
        RedisCache redis;
        public HomeController(ILogger<HomeController> logger, RedisCache redis,IConfiguration config)
        {
            _logger = logger;
            this.redis = redis;
            this.config = config;
        }

        public IActionResult Index()
        {
            HttpContext.Session.SetString("name",$"你好，张三{DateTime.Now}");
            ViewBag.Msg = "Session数据缓存成功";
            //Redis读写操作
            //client.SetString("name",$"张三{DateTime.Now}");
            //指定缓存时过期时间 绝对过期时间
            ////client.SetString("name1", $"张三{DateTime.Now}",new DistributedCacheEntryOptions().SetAbsoluteExpiration(DateTime.Now.AddMinutes(2)));
            //////相对过期时间
            ////client.SetString("name2", $"张三{DateTime.Now}", new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(2)));
            ////ViewBag.Msg = "数据缓存成功";
            var client = new RestClient(config.GetSection("ApiUrl").Value + "product");
            client.GetAsync(new RestRequest(), (response,handler) =>
            {
                redis.SetString("products", response.Content);
            });
            return View();
        }

        public IActionResult Privacy()
        {
           ;
            ViewBag.Msg = $"Session数据读取成功  { HttpContext.Session.GetString("name")}";
            Task<string> products = redis.GetStringAsync("products");
            var data = JsonConvert.DeserializeObject<List<Product>>(products.Result);
            return View(data);
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
